<template>
  <Dialog :title="dialogTitle" v-model="dialogVisible">
    <el-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      label-width="100px"
      v-loading="formLoading"
    >
      <!-- 租户 -->
      <el-form-item label="租户" prop="rechargeTenantId">
        <el-select
          v-model="formData.rechargeTenantId"
          placeholder="请选择租户"
          clearable
          filterable
          class="!w-260px"
        >
          <el-option
            v-for="opt in tenantOptions"
            :key="opt.value"
            :label="opt.label"
            :value="opt.value"
          />
        </el-select>
      </el-form-item>

      <el-form-item label="名单等级" prop="listLevel">
        <el-select v-model="formData.listLevel" placeholder="请选择名单等级" class="!w-260px">
          <el-option
            v-for="dict in getIntDictOptions(DICT_TYPE.LIST_LEVEL)"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>

      <el-form-item label="营销工具" prop="marketingTools">
        <el-select
          v-model="formData.marketingTools"
          placeholder="请选择营销工具"
          clearable
          filterable
          multiple
          class="!w-260px"
        >
          <el-option
            v-for="dict in getStrDictOptions(DICT_TYPE.MARKETING_TOOL)"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>

      <el-form-item label="拉取条数" prop="pullCount">
        <el-input v-model="formData.pullCount" placeholder="请输入拉取条数" class="!w-260px" />
      </el-form-item>

      <el-form-item label="是否启用" prop="enabled">
        <el-radio-group v-model="formData.enabled">
          <el-radio
            v-for="dict in getBoolDictOptions(DICT_TYPE.INFRA_BOOLEAN_STRING)"
            :key="dict.value"
            :label="dict.value"
          >
            {{ dict.label }}
          </el-radio>
        </el-radio-group>
      </el-form-item>
    </el-form>

    <template #footer>
      <el-button @click="submitForm" type="primary" :disabled="formLoading">确 定</el-button>
      <el-button @click="dialogVisible = false">取 消</el-button>
    </template>
  </Dialog>
</template>

<script setup lang="ts">
import {
  getIntDictOptions,
  getBoolDictOptions,
  DICT_TYPE,
  getStrDictOptions
} from '@/utils/dict'
import { PushListConfigApi, PushListConfig } from '@/api/vos/pushlistconfig'
import * as TenantApi from '@/api/system/tenant'

/** 名单推送配置 表单 */
defineOptions({ name: 'PushListConfigForm' })

const { t } = useI18n()
const message = useMessage()

const dialogVisible = ref(false)
const dialogTitle = ref('')
const formLoading = ref(false)
const formType = ref<'create' | 'update'>('create')
const formData = ref<any>({
  id: undefined,
  rechargeTenantId: undefined,
  listLevel: undefined,
  marketingTools: [], // 多选，提交时用逗号拼接
  pullCount: undefined,
  enabled: undefined
})
const formRules = reactive({
  rechargeTenantId: [{ required: true, message: '租户不能为空', trigger: 'change' }],
  listLevel: [{ required: true, message: '名单等级不能为空', trigger: 'change' }],
  marketingTools: [{ required: true, message: '营销工具不能为空', trigger: 'change' }],
  pullCount: [{ required: true, message: '拉取条数不能为空', trigger: 'blur' }],
  enabled: [{ required: true, message: '是否启用 1=启用 0=停用不能为空', trigger: 'change' }]
})
const formRef = ref()

/** 租户下拉 */
type TenantOption = { value: number; label: string }
const tenantOptions = ref<TenantOption[]>([])
const loadTenants = async () => {
  const res = await TenantApi.getTenantList()
  const arr = Array.isArray(res) ? res : (res?.list ?? [])
  tenantOptions.value = arr.map((it: any) => ({
    value: Number(it.id),
    label: it.name || `租户#${it.id}`
  }))
}

/** 打开弹窗 */
const open = async (type: 'create' | 'update', id?: number) => {
  dialogVisible.value = true
  dialogTitle.value = t('action.' + type)
  formType.value = type
  resetForm()

  await loadTenants()

  // 修改时加载数据
  if (id) {
    formLoading.value = true
    try {
      const data: any = await PushListConfigApi.getPushListConfig(id)
      if (data?.rechargeTenantId != null) data.rechargeTenantId = Number(data.rechargeTenantId)
      formData.value = {
        id: data.id,
        rechargeTenantId: data.rechargeTenantId,
        listLevel: data.listLevel,
        marketingTools: data.marketingTools?.split(',') ?? [],
        pullCount: data.pullCount,
        enabled: data.enabled
      }
    } finally {
      formLoading.value = false
    }
  }
}
defineExpose({ open })

/** 提交表单 */
const emit = defineEmits(['success'])
const submitForm = async () => {
  await formRef.value?.validate()
  formLoading.value = true
  try {
    const payload: any = { ...formData.value }
    if (payload.rechargeTenantId != null) {
      payload.rechargeTenantId = Number(payload.rechargeTenantId)
    }
    if (payload.marketingTools) {
      payload.marketingTools = payload.marketingTools.join(',')
    }
    const data = payload as unknown as PushListConfig
    if (formType.value === 'create') {
      await PushListConfigApi.createPushListConfig(data)
      message.success(t('common.createSuccess'))
    } else {
      await PushListConfigApi.updatePushListConfig(data)
      message.success(t('common.updateSuccess'))
    }
    dialogVisible.value = false
    emit('success')
  } finally {
    formLoading.value = false
  }
}

/** 重置表单 */
const resetForm = () => {
  formData.value = {
    id: undefined,
    rechargeTenantId: undefined,
    listLevel: undefined,
    marketingTools: [],
    pullCount: undefined,
    enabled: undefined
  }
  formRef.value?.resetFields?.()
}
</script>
